<?php

namespace App\Repositories;

use App\Enums\GiftOpTypeEnum;
use App\Enums\GiftTypeEnum;
use App\Exceptions\BasicException;

use Illuminate\Support\Facades\DB;

use function Matrix\add;

//引入hash

class GiftRepository
{
    //是否有礼物
    public function getUserGift($user_id, $gift_id)
    {
        $where[] = ['user_id', "=", $user_id];
        $where[] = ['gift_id', "=", $gift_id];

        return app("model_gift_backpack")->where($where)->first();
    }

    /** 管理员送礼
     *
     * @param  int  $user_id  接收者id
     * @param  int  $gift_id  礼物id
     * @param  int  $number  数量
     * @param  string  $remark  送礼备注
     * @param  int  $adminId  操作管理员
     * @throws mixed
     */

    public function sendBackpackGift(int $user_id, int $gift_id, int $number, string $remark, int $adminId)
    {
        $where[] = ['user_id', "=", $user_id];
        $where[] = ['gift_id', "=", $gift_id];
        try {
            DB::beginTransaction();
            if ($this->getUserGift($user_id, $gift_id)) {
                app("model_gift_backpack")->where($where)->increment('number', $number);
            } else {
                app("model_gift_backpack")->create([
                    'user_id' => $user_id,
                    'gift_id' => $gift_id,
                    'number'  => $number,
                ]);
            }
            $insertData = [
                'admin_id' => $adminId,
                'user_id'  => $user_id,
                'gift_id'  => $gift_id,
                'num'      => $number,
                'remark'   => $remark,
            ];
            app('model_admin_give_gift')->create($insertData);//纪录管理员送礼操作
            DB::commit();
        } catch (\Exception $exception) {
            throw new BasicException(10001, "赠送失败");
        }

        return true;
    }

    /**
     * 获取礼物列表
     *
     * @param $where
     * @param $page
     * @param $perPage
     * @return bool
     * @throws BasicException
     */
    public function giftList($where, $page = 1, $perPage = 10)
    {
        $giftList = app('model_gift')->with('gift_frame')->where($where)->where('is_delete', 0)->orderBy('id', 'desc')->paginate($perPage, ['*'], '', $page);
        if ($giftList) {
            return $giftList;
        }
        throw new BasicException(50010);
    }

    public function weekGiftList()
    {
        return app('model_gift')
            ->select(['id','name','picture','type'])
            ->where('type',37)
            ->where('is_delete', 0)
            ->orderBy('id', 'desc')
            ->get()
            ->toArray();
    }

    /**
     * 获取钓鱼礼物列表
     *
     * @param $type
     * @return bool
     */
    public function gameGiftList($type)
    {
        $gameGiftList = app('model_gift')->where('type', $type)->select('id', 'name', 'price', 'picture')->orderBy('id',
            'asc')->get()->toArray();

        return $gameGiftList;
    }

    /*
     * 新增礼物
     * @param $param
     * @return bool
     * @throws BasicException
     *
     * */
    public function addGift($param)
    {
        $addGift = app('model_gift')->create($param);
        if ($addGift) {
            return $addGift;
        }
        throw new BasicException(93020);
    }

    /*
     * 编辑礼物
     * @param $param
     * @return bool
     * @throws BasicException
     * */
    public function saveGift($param)
    {
        $addGift = app('model_gift')->where('id', $param['id'])->update($param);
        if ($addGift !== false) {
            return true;
        }
        throw new BasicException(93024);
    }

    /*
     * 删除礼物
     * @param $param
     * @return bool
     * @throws BasicException
     * */
    public function delGift($param)
    {
        $addGift = app('model_gift')->whereIn('id', $param)->delete();
        if ($addGift) {
            return $addGift;
        }
        throw new BasicException(93021);
    }

    /*
     * 上架或者下架礼物
     * @param $id
     * @param $sold
     * @return bool
     * @throws BasicException
     *
     * */
    public function UpOrDown($id, $sold)
    {
        $UpOrDown = app('model_gift')->where('id', $id)->update(['sold' => $sold]);
        if ($UpOrDown) {
            return $UpOrDown;
        }
        throw new BasicException(93022);
    }

    /*
     * 获取礼物详情
     * @param $id
     * @return bool
     * @throws BasicException
     *
     * */
    public function giftDetail($id)
    {
        $giftDetail = app('model_gift')->with('gift_frame')->where('id', $id)->first()->toArray();
        if ($giftDetail) {
            return $giftDetail;
        }
        throw new BasicException(93023);
    }

    //获取礼物边框列表
    public function getGiftFrameList($where, $page, $perPage)
    {
        $where['deleted'] = 0;
        $giftFrameList = app('model_gift_frame')->where($where)->orderBy('id', 'desc')->paginate($perPage, ['*'], '',
            $page);

        return $giftFrameList;
    }

    public function addGiftFrame($param)
    {
        $param['add_time'] = time();
        $addGift = app('model_gift_frame')->create($param);
        if ($addGift) {
            return $addGift;
        }
        throw new BasicException(93032);
    }

    public function updateGiftFrame($param)
    {
        $gift_frame = app('model_gift_frame')->where('id', $param['id'])->update($param);
        if ($gift_frame !== false) {
            return true;
        }
        throw new BasicException(93033);
    }

    public function delGiftFrame($param)
    {
        app('model_gift_frame')->whereIn('id', $param)->delete();
    }

    public function giftFrameDetail($id)
    {
        return app('model_gift_frame')->where('id', $id)->first();
    }

    //新增或编辑礼物，v350
    public function addOrEdit($param)
    {
        $id = $param['id'] ?? 0;              //主键id
        $module = $param['module'] ?? 1;      //模块：1：房间礼物；2：人脉礼物
        $categoryId = $param['category_id'];  //礼物分类id
        $giftType = $param['gift_type'] ?? 1; //礼物类型
        $opType = $param['op_type'] ?? 0;     //礼物操作类型

        $giftName = $param['gift_name'];
        $giftPrice = $param['gift_price'];
        $unit = $param['unit'] ?? '';
        $picture = $param['picture'];
        $special = $param['special'] ?? '';
        $giftCardiac = $param['gift_cardiac'] ?? 0; //心动值
        $sort = $param['sort'] ?? 0;
        $saleStatus = $param['sale_status']; //销售状态：1：启用；0：禁用
        $giftDesc = $param['gift_desc'] ?? '';
        $giftUrl = $param['gift_url'] ?? '';
        $giftSize = $param['gift_size'] ?? 3;
        $isShowInWall = $param['is_show_in_wall'] ?? 0; //是否在礼物墙展示，1：是；0：否
        $wallStatus = $param['wall_status'] ?? ''; //礼物墙状态
        $wallDesc = $param['wall_desc'] ?? ''; //礼物墙说明
        $prizePoolId = $param['prize_pool_id'] ?? 0; //购买礼物可获得的抽奖奖池id
        $giftTagIds = $param['gift_tag_ids'] ?? ''; //礼物关联的标签id
        $isLock = $param['is_lock'] ?? 0; //是否上锁

        if ($categoryId > 0) {
            $category = app('model_gift_categories')
                ->select('id')
                ->where('id', $categoryId)->where('is_delete', 0)->where('status', 1)
                ->first();
            if (empty($category)) {
                throw new BasicException(0, '分类不存在或已禁用');
            }
        }

        if ($prizePoolId > 0) {
            $prizePoolId = app('model_connect_prize_pool')->where('id', $prizePoolId)->value('id');
            if (empty($prizePoolId)) {
                throw new BasicException(0, '奖池id错误，奖池不存在');
            }
        }

        $newTagIds = [];
        if ($giftTagIds) {
            $newTagIds = $giftTagIds = explode(',', $giftTagIds);
            if (count($newTagIds) > 2) {
                throw new BasicException(0, '最多添加2个礼物标签');
            }

            $tmpGiftTagIds = app('model_gift_tag')
                ->select('id')
                ->whereIn('id', $giftTagIds)->where('status', 1)
                ->pluck('id');
            if (count($giftTagIds) != count($tmpGiftTagIds)) {
                throw new BasicException(0, '礼物标签错误');
            }
        }

        //礼物主表数据
        $giftData = [
            'module'              => $module,
            'category_id'         => $categoryId,
            'type'                => $giftType,
            'op_type'             => $opType,
            'name'                => $giftName,
            'picture'             => $picture,
            'special'             => $special,
            'sort'                => $sort,
            'price'               => $giftPrice,
            'unit'                => $unit,
            'sold'                => $saleStatus == 1 ? 1 : 2,
            'cardiac'             => $giftCardiac,
            'desc'                => $giftDesc,
            'url'                 => $giftUrl,
            'size'                => $giftSize,
            'is_show_in_wall'     => $isShowInWall,
            'wall_status'         => $wallStatus,
            'get_method_desc'     => $wallDesc,
            'prize_pool_group_id' => $prizePoolId,
            'is_lock' => $isLock,
        ];
        if (isset($param['usable_room_sys_type'])) {
            $giftData['room_sys_type'] = $param['usable_room_sys_type']; //可用房间系统类型，0为全部
        }
        //礼物扩展表数据
        //人脉礼物
        $connectExtField = [];
        if (in_array($opType, [GiftOpTypeEnum::CP, GiftOpTypeEnum::STUDENT, GiftOpTypeEnum::FRIEND])) {
            $connectExtField['relation_name'] = $param['relation_name'] ?? ''; //人脉关系名称
            $connectExtField['connect_level'] = $param['connect_level'];       //人脉关系等级
        }
        //魔法礼物
        $magicExtFields = [];
        if (in_array($opType, array_keys(GiftOpTypeEnum::MAGIC))) {
            $magicExtFields = ['special_list' => [], 'success_probability' => 100, 'magic_time' => 0, 'is_shock' => 0, 'delay_shock' => 0];
            //装扮礼物
            if ($opType == GiftOpTypeEnum::DRESS_UP) {
                $magicExtFields['special_list'] = explode(',', $param['special_list']); //特效url列表
                $magicExtFields['magic_time'] = $param['magic_time'];                   //魔法时间
            }
            //闭麦礼物
            if ($opType == GiftOpTypeEnum::OFF_MICROPHONE) {
                $magicExtFields['success_probability'] = $param['success_probability']; //闭麦成功率
                $magicExtFields['magic_time'] = $param['magic_time'];
            }
            //乌贼和碎屏
            if ($opType == GiftOpTypeEnum::SQUID || $opType == GiftOpTypeEnum::BROKEN_SCREEN) {
                $magicExtFields['is_shock'] = $param['is_shock'];       //是否振动
                $magicExtFields['delay_shock'] = $param['delay_shock']; //振动延时的秒数
            }
        }

        DB::beginTransaction();
        try {
            if ($id > 0) { //编辑礼物

                $gift = app('model_gift')->where('id', $id)->value('id');
                if (empty($gift)) {
                    throw new BasicException(0, 'id错误，记录不存在');
                }

                app('model_gift')->where('id', $id)->update($giftData);

                //更新礼物扩展字段
                if ($connectExtField) {
                    app('model_gift_extend')->where('gift_id', $id)->update($connectExtField);
                } else {
                    if ($magicExtFields) {
                        app('model_gift_extend')->where('gift_id', $id)->update(['magic_ext' => json_encode($magicExtFields)]);
                    }
                }

                //原始标签
                $originalTagIds = app('model_gift_tag_join')->select('tag_id')->where('gift_id', $id)->pluck('tag_id')->toArray();
            } else { //新增礼物

                $id = app('model_gift')->insertGetId($giftData);

                //新增礼物扩展
                if ($connectExtField) {
                    $connectExtField['gift_id'] = $id;
                    app('model_gift_extend')->insert($connectExtField);
                } else {
                    if ($magicExtFields) {
                        app('model_gift_extend')->insert(['gift_id' => $id, 'magic_ext' => json_encode($magicExtFields)]);
                    }
                }

                //原始标签
                $originalTagIds = [];
            }

            //礼物标签维护
            $rmTagIds = array_diff($originalTagIds, $newTagIds);
            $addTagIds = array_diff($newTagIds, $originalTagIds);
            if ($rmTagIds) {
                foreach ($rmTagIds as $rmTagId) {
                    app('model_gift_tag_join')->where('gift_id', $id)->where('tag_id', $rmTagId)->delete();
                }
            }
            if ($addTagIds) {
                foreach ($addTagIds as $addTagId) {
                    app('model_gift_tag_join')->insert(['gift_id' => $id, 'tag_id' => $addTagId]);
                }
            }

            DB::commit();

            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    //新增或编辑套装，v350
    public function addOrEditSuit($param)
    {
        $id = $param['id'] ?? 0;
        $module = $param['module'] ?? 1; //模块：1：房间礼物；2：人脉礼物；3：礼物墙
        $opType = $param['op_type'];
        $giftName = $param['gift_name'];
        $picture = $param['picture'];
        $sort = $param['sort'] ?? 0;
        $saleStatus = $param['sale_status']; //销售状态：1：启用；0：禁用
        $giftDesc = $param['gift_desc'] ?? '';
        $joinGiftInfo = json_decode($param['join_gift_info'], true);

        if (empty($joinGiftInfo)) {
            throw new BasicException(0, '请选择套装礼物');
        }

        if (!is_array($joinGiftInfo)) {
            throw new BasicException(0, '礼物参数格式错误');
        }

        foreach ($joinGiftInfo as &$giftInfo) {
            $giftId = app('model_gift')->where('id', $giftInfo['gift_id'])->value('id');
            if (empty($giftId)) {
                throw new BasicException(0, '礼物参数错误');
            }
            $giftInfo = json_encode($giftInfo);
        }

        //礼物主表数据
        $giftData = [
            'op_type' => $opType,
            'module'  => $module,
            'name'    => $giftName,
            'picture' => $picture,
            'sort'    => $sort,
            'sold'    => $saleStatus == 1 ? 1 : 2,
            'desc'    => $giftDesc,
        ];

        DB::beginTransaction();
        try {
            if ($id > 0) { //编辑

                app('model_gift')->where('id', $id)->update($giftData);

                //原套装关联礼物id
                $originalGifts = app('model_gift_suit_join')
                    ->select('gift_id', 'is_rare')
                    ->where('suit_id', $id)
                    ->get()->toArray();
                foreach ($originalGifts as &$originalGift) {
                    $originalGift = json_encode($originalGift);
                }
            } else { //新增

                $id = app('model_gift')->insertGetId($giftData);

                //原套装关联礼物id
                $originalGifts = [];
            }

            //关联礼物维护
            $rmGifts = array_diff($originalGifts, $joinGiftInfo);
            $addGifts = array_diff($joinGiftInfo, $originalGifts);
            if ($rmGifts) {
                foreach ($rmGifts as $rmGift) {
                    $rmGift = json_decode($rmGift, true);
                    app('model_gift_suit_join')
                        ->where('suit_id', $id)->where('gift_id', $rmGift['gift_id'])
                        ->delete();
                }
            }
            if ($addGifts) {
                foreach ($addGifts as $addGift) {
                    $addGift = json_decode($addGift, true);
                    if (!isset($addGift['gift_id'])) {
                        throw new BasicException(0, '请选择礼物');
                    }
                    if (!isset($addGift['is_rare'])) {
                        throw new BasicException(0, '请选择是否设置稀有');
                    }
                    app('model_gift_suit_join')->insert([
                        'suit_id' => $id,
                        'gift_id' => $addGift['gift_id'],
                        'is_rare' => $addGift['is_rare'],
                    ]);
                }
            }

            DB::commit();

            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage() . '|' . $e->getLine());
        }
    }

    //礼物信息格式转化
    private function giftInfoTransfer($giftInfo)
    {
        $newGiftInfo = [];
        foreach ($giftInfo as $v) {
            $newGiftInfo[] = $v['gift_id'] . ',' . $v['is_rare'];
        }

        return $newGiftInfo;
    }

    //新增或编辑说明背景，v350
    public function addOrEditDescBg($param)
    {
        $id = $param['id'] ?? 0;
        $bgImgUrl = $param['bg_img_url'];
        $status = $param['status'];

        $data = [
            'img_url' => $bgImgUrl,
            'status'  => $status,
        ];

        if ($id > 0) {
            $descBgId = app('model_gift_desc_bg')->where('id', $id)->value('id');
            if (empty($descBgId)) {
                throw new BasicException(0, 'id错误，记录不存在');
            }

            $res = app('model_gift_desc_bg')->where('id', $id)->update($data);
        } else {
            $res = app('model_gift_desc_bg')->insert($data);
        }

        return $res;
    }

    //新增或编辑礼物分类，v350
    public function addOrEditCategory($param)
    {
        $id = $param['id'] ?? 0;
        $parentId = $param['parent_category_id'] ?? 0;
        $categoryName = $param['category_name'];
        $giftDescBgId = $param['gift_desc_bg_id'];
        $sort = $param['sort'];
        $status = $param['status'];

        $data = [
            'title'           => $categoryName,
            'parent_id'       => $parentId,
            'gift_desc_bg_id' => $giftDescBgId,
            'sort'            => $sort,
            'status'          => $status,
            'update_time'     => time(),
        ];

        if ($id > 0) {
            $res = app('model_gift_categories')->where('id', $id)->update($data);
        } else {
            $data['create_time'] = time();
            $res = app('model_gift_categories')->insert($data);
        }

        return $res;
    }

    //赠送礼物
    public function give($giftId, $giftNum, $userId = 0, $userCode = 0,$remark = "",$admin=0)
    {
        if (empty($userId)) {
            if ($userCode) {
                $userId = app('model_user_data')->select('user_id')->where('user_code', $userCode)->value('user_id');
                if (empty($userId)) {
                    throw new BasicException(0, '用户编号不存在');
                }
            } else {
                throw new BasicException(0, '参数缺失');
            }
        }
        $userId = app('model_user')
            ->select('user_id')
            ->where('user_id', $userId)->where('deleted', 0)
            ->value('user_id');
        if (empty($userId)) {
            throw new BasicException(0, '用户不存在或已注销');
        }

        //查询礼物信息
        $gift = app('model_gift')->select('is_lock')->where('id', $giftId)->first();
        if (empty($gift)) throw new BasicException(0, '礼物id错误');

        //赠送到用户背包
        $where = ['user_id' => $userId, 'gift_id' => $giftId];
        $backpackGift = app('model_gift_backpack')->select('id', 'number')->where($where)->first();
        if ($backpackGift) {
            if ($gift->is_lock == 1 && $backpackGift->number == 0 && $backpackGift->is_lock == 0) {
                $backpackGift->is_lock = 1;
            }
            $backpackGift->number += $giftNum;
            $backpackGift->save();
        } else {
            app('model_gift_backpack')->insert([
                'user_id' => $userId,
                'gift_id' => $giftId,
                'number'  => $giftNum,
                'is_lock'  => $gift->is_lock,
            ]);
        }
        $insertData = [
            'admin_id' => $admin,
            'user_id'  => $userId,
            'gift_id'  => $giftId,
            'num'      => $giftNum,
            'remark'   => $remark,
        ];
        return app('model_admin_give_gift')->create($insertData);//纪录管理员送礼操作
    }
}
